<template>
  <el-dialog
    v-el-drag-dialog
    title="回执确认"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <el-form ref="dataForm" inline :rules="rules" :model="temp">
      <el-descriptions size="medium" :column="2" style="margin-bottom: 20px;">
        <el-descriptions-item label="客户编号">{{ order.csmCode }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ order.csmName }}</el-descriptions-item>
        <el-descriptions-item label="客户地址">{{ order.csmAddress }}</el-descriptions-item>
      </el-descriptions>
      <el-form-item label="责任机构:" prop="orgSNNo">
        <el-tree-select
          v-model="temp.orgSNNo"
          disabled
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': false,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="配送员:" prop="userId">
        <el-select v-model="temp.userId" disabled :loading="$loadingPlugin.getOwnersListNew" style="width: 120px;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:" prop="paymentMethod">
        <el-select v-model="temp.paymentMethod" style="width: 150px;" disabled placeholder="请选择" @change="paymentChange">
          <el-option
            v-for="item in paymentMethodMapClone"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="确认人:" prop="reCheckUserName">
        <el-input v-model="temp.reCheckUserName" :disabled="allDisabled" style="width: 100px;" />
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      class="table"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      :immediate-fetch="false"
      :summary-method="getSummaries"
      show-summary
      @fetch="fetchData"
    />
    <el-descriptions size="medium" :column="4" style="margin-top: 20px;" :label-style="{'color': '#F24024'}" :content-style="{'color': '#F24024'}">
      <el-descriptions-item label="总应收">{{ totalTreceivable }}</el-descriptions-item>
      <el-descriptions-item label="总实收">{{ totalReflections }}</el-descriptions-item>
      <el-descriptions-item v-if="tableData.data.some(item => item.pricingMode === 2)" label="总送出重量">{{ totalGasWeight }}</el-descriptions-item>
      <el-descriptions-item v-if="tableData.data.some(item => item.pricingMode === 2)" label="总回收重量">{{ totalFee3 }}</el-descriptions-item>
    </el-descriptions>
    <div slot="footer" class="dialog-footer">
      <div v-show="order.isRePay === 2" class="footer-tip">已二次支付，待确认回执</div>
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button v-if="corpSettingData.sp6 >> 28 & 0x01 && order.paymentMethod === 1 && order.isRePay === 1" :loading="$loadingPlugin.success" type="primary" @click="showSecondPayDialog">
        二次支付
      </el-button>
      <el-button v-else :loading="$loadingPlugin.success" type="primary" @click="success">
        确认回执
      </el-button>
    </div>
    <prepaid-card ref="prepaidCard" />
    <second-pay ref="secondPay" @paySuccess="success1" @confirmPaySuccess="handleConfirmPaySuccess" />
  </el-dialog>
</template>

<script>
  import {
    querySignOrderOrderBillData,
    queryCsmCardCodeByOrderCode,
    submitReceiptConfirm,
    queryOwnerList,
    csDeliverUserList,
    querySpecListAll,
    removePaymentMethod
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import PrepaidCard from './PrepaidCard'
  import SecondPay from './SecondPay.vue'
  import { formatColumnMap } from '@/utils'

  export default {
    name: 'receipt-confirm',
    components: {
      PrepaidCard,
      SecondPay
    },
    props: {
      paymentMethodMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        treeData: [],
        ownersList: [],
        showCsmCard: false, // 是否显示预付卡
        payDisabled: false, // 支付方式是否禁用
        allDisabled: false, // 是否禁用掉所有选项[责任机构、配送员、支付方式、确认人]
        check_csmCard_ok_info: {
          check_csmCard_ok_status: false, // 是否校验通过预付卡密码或验证码 true表示校验通过 false表示校验失败
          check_csmCard_ok_msg: ''
        },
        paymentMethodMapClone: [],
        csmName: '',
        csmPhone: '',
        row: {},
        temp: {
          orgSNNo: '',
          userId: '',
          paymentMethod: 1,
          reCheckUserName: ''
        },
        rules: {
          userId: [{ required: true, message: '请选择配送员', trigger: 'change' }],
          reCheckUserName: [{ required: true, message: '请输入确认人', trigger: 'change' }],
          paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }]
        },
        detail: {},
        specList: [],
        order: {
          treceivables: 0
        },
        tableData: {
          column: [
            {
              type: 'index'
            },
            {
              prop: 'goodsName',
              width: 120,
              label: '商品名称'
            },
            {
              prop: 'specCode',
              label: '规格型号',
              width: 180,
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit && scope.row.pricingMode === 2 ? (
                    <el-select
                      value={scope.row[scope.column.property]}
                      onChange={val => {
                        scope.row[scope.column.property] = val
                      }}
                    >
                      {this.specList.map(option => {
                        return (
                          <el-option
                            label={option.specName}
                            value={option.specCode}
                          ></el-option>
                        )
                      })}
                    </el-select>
                  ) : (
                    <span>
                      {formatColumnMap(this.specList, 'specCode', scope.row[scope.column.property], 'specName')}
                    </span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'gcount',
              align: 'right',
              label: '数量',
              render: (h, scope) => scope.row._edit && scope.row.pricingMode === 2 ? <el-input v-model={scope.row[scope.column.property]} onInput={val => scope.row[scope.column.property] = val.replace(/[^\d]/g, '')} size='mini' /> : <span>{ scope.row[scope.column.property]}</span>
            },
            {
              prop: 'gasWeight',
              align: 'right',
              width: 110,
              label: '送出重量',
              render: (h, scope) => scope.row._edit && scope.row.pricingMode === 2 ? <el-input-number v-model={scope.row[scope.column.property]} controls={false} min={0} max={9999} precision={2} onInput={val => scope.row[scope.column.property] = val} size='mini' /> : <span class='right'>{ scope.row[scope.column.property]}</span>
            },
            {
              prop: 'fee3',
              align: 'right',
              width: 110,
              label: '回收重量',
              render: (h, scope) => scope.row._edit && scope.row.pricingMode === 2
                ? <el-input-number v-model={scope.row[scope.column.property]} controls={false} min={0} max={9999}
                                 precision={2} onInput={val => scope.row[scope.column.property] = val} size='mini'
                /> : <span class='right'>{scope.row[scope.column.property]}</span>
            },
            {
              prop: 'netWeight',
              align: 'right',
              label: '净重',
              formatter: row => row.netWeight ? row.netWeight : '0.00'
            },
            {
              prop: 'gprince',
              align: 'right',
              label: '单价'
            },
            {
              prop: 'gprefPrice',
              align: 'right',
              label: '优惠价格'
            },
            {
              prop: 'fee1',
              align: 'right',
              label: '远距配送费'
            },
            {
              prop: 'fee2',
              align: 'right',
              label: '上楼费'
            },
            {
              prop: 'tip',
              align: 'right',
              label: '服务费'
            },
            {
              prop: 'treceivable',
              align: 'right',
              label: '总应收',
              render: (h, { row }) => <span>{ row.treceivable ? Number(row.treceivable).toFixed(2) : '0.00' }</span>
            },
            {
              prop: 'accReceivable',
              align: 'right',
              width: 100,
              label: '实收金额',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit
                        ? <el-input value={ scope.row[scope.column.property] } onInput={ (val) => { scope.row[scope.column.property] = val.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/, '$1') } }></el-input>
                        : <span>{ scope.row[scope.column.property] ? Number(scope.row[scope.column.property]).toFixed(2) : '' }</span>
                    }
                  </div>
                )
              }
            },
            {
              label: '操作',
              width: 80,
              alignt: 'center',
              fixed: 'right',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      (scope.row.paymentMethod === 1 || scope.row.paymentMethod === 16) && scope.row.reStatus === 2 &&
                      <div>
                        {scope.row._edit
                        ? <div>
                          <el-link underline={false} onClick={ () => { this.handleSave(scope) } }>保存</el-link>
                          <el-link underline={false} type='danger' onClick={ () => { this.handleCancle(scope) } }>取消</el-link>
                        </div>
                        : this.corpSettingData.sp6 >> 9 & 0x01 || this.corpSettingData.sp6 >> 28 & 0x01 ? <span></span> : <el-link underline={false} onClick={ () => { this.handleEdit(scope) } }>编辑</el-link>}
                      </div>
                    }
                  </div>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData', 'userInfo'
      ]),
      // 总应收
      totalTreceivable: function() {
        let count = 0
        if (this.tableData.data.length > 0) count = this.tableData.data.reduce((prev, cur) => prev + Number(cur.treceivable), 0)
        return isNaN(count) ? '0.00' : count.toFixed(2)
      },
      // 总实收
      totalReflections: function() {
        let count = 0
        if (this.tableData.data.length > 0) count = this.tableData.data.reduce((prev, cur) => prev + Number(cur.accReceivable), 0)
        return isNaN(count) ? '0.00' : count.toFixed(2)
      },
      // 总送出重量
      totalGasWeight: function() {
        let count = 0
        if (this.tableData.data.length > 0) count = this.tableData.data.reduce((prev, cur) => prev + Number(cur.gasWeight), 0)
        return isNaN(count) ? '0.00' : count.toFixed(2)
      },
      // 总回收重量
      totalFee3: function() {
        let count = 0
        if (this.tableData.data.length > 0) count = this.tableData.data.reduce((prev, cur) => prev + Number(cur.fee3), 0)
        return isNaN(count) ? '0.00' : count.toFixed(2)
      }
    },
    created() {
      this.getGoodsSpecList()
    },
    methods: {
      async open(temp) {
        if (temp) this.row = temp
        this.paymentMethodMapClone = JSON.parse(JSON.stringify(this.paymentMethodMap))
        await Promise.all([
          this.getTreeData(),
          // this.getOwnersList(temp.orgId),
          this.getOwnersListNew(temp.orgId),
          this.getShowCsmCardValue()])
        this.init()
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            if (temp.reStatus === 1) {
              this.$message('温馨提示：该订单无需回执')
            }
            const owner = this.ownersList.find(item => item.userId === temp.ownerId)
            const orgInfo = this.orgList.find(item => item.orgSNNo === temp.orgSNNo)
            this.temp.orgSNNo = orgInfo ? orgInfo.orgSNNo : ''
            this.temp.orgId = orgInfo ? orgInfo.orgId : ''
            if (owner) this.temp.userId = temp.ownerId
            else this.temp.userId = ''
            this.temp.reCheckUserName = this.userInfo.userName
            this.detail = temp
            this.csmName = temp.csmName
            this.csmPhone = temp.csmPhone
            this.temp.paymentMethod = temp.paymentMethod
            this.removePaymentMethod()
            this.$nextTick(() => {
              this.$refs.lbTable.fetch({ currentPage: 1 })
            })
          }
        })
      },
      // 查询是否显示预付卡
      async getShowCsmCardValue() {
        const idx = this.paymentMethodMapClone.findIndex(item => item.value === 8)
        this.paymentMethodMapClone.splice(idx, 1) // 支付方式下拉框去掉优惠券
        // if (!this.showCsmCard) {
        //   const index = this.paymentMethodMapClone.findIndex(item => item.value === 256)
        //   this.paymentMethodMapClone.splice(index, 1) // 删除预付卡
        // }
      },
      async removePaymentMethod() {
        const res = await removePaymentMethod({ csmId: this.row.csmId, orgId: this.temp.orgId })
        if (res.data && res.data.length > 0) {
          const removeArr = res.data
          const paymentMethodMap = JSON.parse(JSON.stringify(this.paymentMethodMap))
          removeArr.forEach((item) => {
            const idx = paymentMethodMap.findIndex(item2 => item2.value === item)
            if (idx > -1) {
              paymentMethodMap.splice(idx, 1)
            }
          })
          this.paymentMethodMapClone = paymentMethodMap
          const values = this.paymentMethodMapClone.map(item => item.value)
          if (values.indexOf(this.temp.paymentMethod) === -1) {
            this.temp.paymentMethod = ''
          }
        } else {
          this.paymentMethodMapClone = JSON.parse(JSON.stringify(this.paymentMethodMap))
          const values = this.paymentMethodMapClone.map(item => item.value)
          if (values.indexOf(this.temp.paymentMethod) === -1) {
            this.temp.paymentMethod = ''
          }
        }
      },
      init() {
        const data = this.paymentMethodMap
        let text = ''
        const values = []
        for (let i = 0; i < data.length; i++) {
          var item = data[i]
          if (item.value === -1) {
            continue
          }
          if (item.value & this.row.paymentMethod) {
            if (!text) {
              text += item.text
            } else {
              text += ','
              text += item.text
            }
            values.push(item.value)
          }
        }
        if (values.length === 1) {
          this.$set(this.temp, 'paymentMethod', this.row.paymentMethod)
          if (values[0] === 2 || values[0] === 16 || values[0] === 32 || values[0] === 64 || values[0] === 128 || values[0] === 256 || values[0] === 512 || values[0] === 1024 || this.corpSettingData.sp6 >> 9 & 0x01) {
            this.payDisabled = true
          }
          // 当支付类型为预付卡、月结 或者配置回执不可编辑打开的情况下 责任机构、配送员、支付方式、确认人全部禁用  回执二次确认打开也禁止编辑
          if (values[0] === 16 || values[0] === 256 || this.corpSettingData.sp6 >> 9 & 0x01 || this.corpSettingData.sp6 >> 28 & 0x01) {
            this.allDisabled = true
          }
        }
      },
      // 支付方式改变
      async paymentChange(value) {
        // 支付方式修改,则重置预付卡验证状态
        this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_status', false)
        this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_msg', '')
        // 预支付并且之前订单不是预付卡支付
        if (value === 256 && this.order.paymentMethod !== 256) {
          // 结束编辑
          if (this.tableData.data.some(item => item._edit)) {
            this.$message.warning('请结束编辑！')
            return
          }
          // 校验预支付账号是否存在,预支付金额是否足够支付
          this.selectCsmCardCodeByOrderCode()
        }
      },
      // 根据批发订单查询客户预付卡
      async selectCsmCardCodeByOrderCode() {
        const res = await queryCsmCardCodeByOrderCode({
          orderCode: this.detail.orderCode,
          billType: 1,
          payMoney: this.totalReflections
        })
        // 客户可用预付卡卡号
        // const cardCode = res.data.cardCode
        const checkWay = res.data.accCsmCardConfigInfo.checkWay
        // 规则配置不是无校验
        if (checkWay !== 1) {
          // 打开预付卡弹框
          this.$refs.prepaidCard.open(res.data)
        } else {
          this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_status', true)
          this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_msg', '')
        }
      },
      // 获取责任机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 获取详情数据
      async fetchData() {
        const res = await querySignOrderOrderBillData({ orderCode: this.row.orderCode })
        this.order = res.data
        this.order.treceivables = res.data.treceivables
        this.tableData.data = res.data.detailList
        this.tableData.data.forEach((item) => {
          item.paymentMethod = this.row.paymentMethod
          item.reStatus = this.row.reStatus
        })
        console.log(this.tableData.data)
        this.tableData.defaultData = JSON.parse(JSON.stringify(this.tableData.data))
        let hasPricingMode2 = false // 是否有按单位计价的商品
        for (let i = 0; i < res.data.detailList.length; i++) {
          if (res.data.detailList[i].pricingMode === 2) {
            hasPricingMode2 = true
          }
          const detail = res.data.detailList[i]
          // 净气未完成的，实收为空;普通商品实收默认应收
          if (this.order.orderStatus !== 10) {
            if (detail.pricingMode === 2) {
              detail.accReceivable = null
            } else {
              if (this.order.payStatus === 1) {
                detail.accReceivable = detail.treceivable
              }
            }
          }
          detail.gasWeight = (detail.fee3 || 0) + (detail.netWeight || 0)
          if (detail.gasWeight === 0) {
            detail.gasWeight = null
          }
        }
        if (hasPricingMode2 === false && this.order.orderStatus !== 10) {
          if (this.order.payStatus === 1) {
            this.order.taccReceivable = this.order.treceivables
          }
        }
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.temp.orgId = value.orgId
        // this.getOwnersList(value.orgId)
        this.getOwnersListNew(value.orgId)
        if (!this.payDisabled) {
          this.temp.paymentMethod = ''
        }
        this.$set(this.temp, 'userId', '')
        this.removePaymentMethod()
      },
      // 查询处理人列表
      async getOwnersList(orgId) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownersList = res.data
      },
      // 查询处理人列表（新）
      async getOwnersListNew(orgId) {
        const res = await csDeliverUserList({ deliveryOrgId: orgId })
        this.ownersList = res.data.filter(item => item.userId !== this.ownerId)
      },
      async success() {
        if (this.tableData.data.some(item => item._edit)) {
          this.$message.error('请结束编辑！')
          return
        }
        const rows = this.tableData.data
        for (let i = 0; i < rows.length; i++) {
          if (rows[i].pricingMode === 2) {
            if (!rows[i].gasWeight || rows[i].gasWeight * 1 <= 0) {
              this.$message.error(`请填写${rows[i].goodsName}的送出重量`)
              return
            }
            if (rows[i].accReceivable === '' || rows[i].accReceivable == null) {
              this.$message.error(`请填写${rows[i].goodsName}的实收金额`)
              return
            }
            if (!rows[i].specCode) {
              this.$message.error('请选择规格')
              return
            }
          }
        }
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const rows = this.tableData.data
          // for (let i = 0; i < this.paymentMethodMapClone.length; i++) {
          //   // 支付方式存在预支付
          //   if (this.order.payStatus !== 3 && this.paymentMethodMapClone[i].value === 256) {
          //     if (!this.check_csmCard_ok_info.check_csmCard_ok_status) {
          //       if (this.check_csmCard_ok_info.check_csmCard_ok_msg === '') {
          //         this.$message.warning('使用预支付需要校验密码或验证码')
          //         return
          //       } else {
          //         this.$message.warning(`${this.check_csmCard_ok_info.check_csmCard_ok_msg}`)
          //         return
          //       }
          //     }
          //   }
          // }
          const matchOrg = this.orgList.find(item => item.orgSNNo === this.temp.orgSNNo)
          const matchUser = this.ownersList.find(item => item.userId === this.temp.userId)
          const params = {
            paymentMethod: this.temp.paymentMethod,
            tReceivables: this.order.tReceivables,
            taccReceivable: this.totalReflections,
            accReceivable: this.totalReflections,
            reCheckUserName: this.temp.reCheckUserName,
            orgId: matchOrg.orgId,
            orgName: matchOrg.orgName,
            orgSNNo: matchOrg.orgSNNo,
            ownerId: matchUser.userId,
            ownerName: matchUser.userName,
            ownerCode: matchUser.userCode,
            orderCode: this.order.orderCode,
            relBackGas: this.order.relBackGas,
            generalGas: this.order.generalGas,
            detailList: rows
          }
          if (this.order.corpCode === '37049' && this.order.relBackGas > 0 && params.relBackGas === 0) {
            params.relBackGas = this.order.relBackGas
          }
          let msg = '实收金额:' + params.taccReceivable + '，确认提交吗？'
          if (this.order.orderStatus < 10) {
            // msg = "<span style='color:red;font-weight:bold'>此订单未完成</span><br/>" + msg
            msg = '此订单未完成!!!' + msg
          }
          this.$confirm(`${msg}`, '提示', {
            type: 'warning'
          }).then(() => {
            const loading = this.$message({
              message: '正在提交',
              duration: 0,
              iconClass: 'el-icon-loading'
            })
            submitReceiptConfirm(params).then(() => {
              this.resolve()
              this.visible = false
              this.$notify({
                title: '提示',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
            }).finally(() => {
              loading.close()
            })
          })
        })
      },
      // 用于二次支付支付成功后自动调用回执确认接口 与success手动调用区分
      async success1() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const rows = this.tableData.data
          const matchOrg = this.orgList.find(item => item.orgSNNo === this.temp.orgSNNo)
          const matchUser = this.ownersList.find(item => item.userId === this.temp.userId)
          const params = {
            paymentMethod: this.temp.paymentMethod,
            tReceivables: this.order.tReceivables,
            taccReceivable: this.totalReflections,
            accReceivable: this.totalReflections,
            reCheckUserName: this.temp.reCheckUserName,
            orgId: matchOrg.orgId,
            orgName: matchOrg.orgName,
            orgSNNo: matchOrg.orgSNNo,
            ownerId: matchUser.userId,
            ownerName: matchUser.userName,
            ownerCode: matchUser.userCode,
            orderCode: this.order.orderCode,
            relBackGas: this.order.relBackGas,
            generalGas: this.order.generalGas,
            detailList: rows
          }
          if (this.order.corpCode === '37049' && this.order.relBackGas > 0 && params.relBackGas === 0) {
            params.relBackGas = this.order.relBackGas
          }
          // let msg = '实收金额:' + params.taccReceivable + '，确认提交吗？'
          // if (this.order.orderStatus < 10) {
          //   // msg = "<span style='color:red;font-weight:bold'>此订单未完成</span><br/>" + msg
          //   msg = '此订单未完成!!!' + msg
          // }
          submitReceiptConfirm(params)
        })
      },
      handleConfirmPaySuccess() {
        this.resolve()
        this.visible = false
      },
      handleEdit(scope) {
        this.$set(scope.row, '_edit', true)
      },
      handleSave(scope) {
        scope.row.netWeight = ((scope.row.gasWeight || 0) * 1 - (scope.row.fee3 || 0) * 1).toFixed(2)
        var treceivable = 0
        let tempAccReceivable
        if (scope.row.pricingMode === 2) {
          treceivable = (scope.row.gprince - (scope.row.gprefPrice || 0) * 1) * ((scope.row.netWeight || 0) * 1) +
            scope.row.fee1 * 1 + scope.row.fee2 * 1 + scope.row.tip * 1 + (scope.row.checkPrice || 0) * 1
          if (treceivable < 0) {
            treceivable = 0
          }
        } else {
          treceivable = (scope.row.checkPrice || 0) * 1 + scope.row.treceivable * 1
        }
        treceivable = treceivable.toFixed(2)
        if (this.order.payStatus > 1) {
          tempAccReceivable = scope.row.accReceivable
        } else {
          tempAccReceivable = treceivable
        }
        scope.row.treceivable = treceivable
        scope.row.accReceivable = tempAccReceivable
        if (scope.row.pricingMode === 2) {
          if (!scope.row.gasWeight || scope.row.gasWeight * 1 <= 0) {
            this.$message.warning('请填写送出重量')
            return
          }
          if (scope.row.accReceivable === '' || scope.row.accReceivable == null) {
            this.$message.warning('请填写实收金额')
            return
          }
          if (!scope.row.specCode) {
            this.$message.warning('请选择规格')
            return
          }
        }
        this.$set(scope.row, '_edit', false)
        this.$set(this.tableData.defaultData, scope.$index, JSON.parse(JSON.stringify(scope.row)))
        this.$set(this.tableData.data, scope.$index, JSON.parse(JSON.stringify(scope.row)))
      },
      handleCancle(scope) {
        this.$set(this.tableData.data, scope.$index, JSON.parse(JSON.stringify(this.tableData.defaultData[scope.$index])))
      },
      // 规格型号列表
      async getGoodsSpecList() {
        const res = await querySpecListAll({
          currentPage: 1,
          pageSize: 999
        })
        this.specList = res.data.rows
      },
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if ([0, 7, 8, 9, 10, 11].includes(index)) {
            sums[index] = ''
            return
          }
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })
        sums[4] = isNaN(sums[4]) ? '0.00' : sums[4].toFixed(2)
        sums[5] = isNaN(sums[5]) ? '0.00' : sums[5].toFixed(2)
        sums[6] = isNaN(sums[6]) ? '' : sums[6].toFixed(2)
        sums[12] = isNaN(sums[12]) ? '' : sums[12].toFixed(2)
        sums[13] = isNaN(sums[13]) ? '' : sums[13].toFixed(2)
        return sums
      },
      async showSecondPayDialog() {
        // 二次支付前先验证是否支付成功，避免获取二维码失败
        const res = await querySignOrderOrderBillData({ orderCode: this.row.orderCode })
        if (res.data && res.data.isRePay === 2) {
          return this.$message.warning('该订单已二次支付成功，请勿重复支付')
        }
        // 打开二次支付
        this.$refs.secondPay.open(this.order)
      },
      reset() {
        this.temp = {
          orgSNNo: '',
          orgId: '',
          userId: '',
          paymentMethod: 1,
          reCheckUserName: ''
        }
        this.tableData.data = []
        this.tableData.defaultData = []
        this.showCsmCard = false
        this.payDisabled = false
        this.allDisabled = false
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.table {
  /deep/ .cell .right {
    display: inline-block;
    width: 100%;
    text-align: right;
  }
  /deep/ .el-input-number {
    width: 88px;
    padding-right: 5px;
    padding-left: 5px;
  }
}
.dialog-footer {
  .footer-tip {
    float: left;
    color: red;
  }
}
</style>
